from datetime import datetime
from app.api.deps import SessionDep, get_db
from app.crud import get_speech_data_by_date, get_zentao_data_by_date
import httpx
from loguru import logger


async def upload_daily_data():
    """每天 23:50 执行的数据上传任务"""
    try:
        logger.info(f"🚀 开始执行每日数据上传任务 - {datetime.now()}")

        for session in get_db():  # 如果 get_db 是 async generator
            source_data_list = get_speech_data_by_date(
                session=session, date=datetime.now()
            )
            source_zentao_data_list = get_zentao_data_by_date(
                session=session, date=datetime.now()
            )
            data_list = []
            zentao_data_list = []
            logger.info(
                f"🔍 查询到 {len(source_data_list)} 条语音数据，{len(source_zentao_data_list)} 条禅道数据，准备上传..."
            )

            for data in source_data_list:
                data_list.append(
                    {
                        "language": data.language,
                        "languageName": data.language_name,
                        "project": data.project,
                        "owner": data.user,
                        "content": data.content,
                        "text": data.desc,
                        "feedbackStatus": data.feedback,
                        "dept": data.dept,
                    }
                )
            for data in source_zentao_data_list:
                zentao_data_list.append(
                    {
                        "project": data.project,
                        "owner": data.user,
                    }
                )
            logger.info(f"语音数据详情: {data_list}")
            logger.info(f"禅道数据详情: {zentao_data_list}")
            # 👇 替换为你的真实上传逻辑
            async with httpx.AsyncClient() as client:
                headers = {"Content-Type": "application/json"}
                speech_response = await client.post(
                    "http://192.168.142.225:66/testdomain/synthesis/add/batch",
                    headers=headers,
                    json=data_list,
                    timeout=30.0,
                )

            async with httpx.AsyncClient() as client:
                headers = {"Content-Type": "application/json"}
                zentao_response = await client.post(
                    "http://192.168.142.225:66/testdomain/zentao/add/batch",
                    headers=headers,
                    json=zentao_data_list,
                    timeout=30.0,
                )
            speech_response.raise_for_status()  # 抛出异常如果失败
            zentao_response.raise_for_status()  # 抛出异常如果失败

        logger.info(f"✅ 数据上传成功 - {datetime.now()}")

    except Exception as e:
        logger.error(f"❌ 数据上传失败: {e}")
